/**
 * Copyright 2007 Sensatic.org
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.sensatic.dynawork.groovy;


/**
 * Groovy builder that works with Stax processors
 * 
 * @author <a href="dejan@nighttale.net">Dejan Bosanac</a>
 */
import groovy.util.BuilderSupport;

import java.util.Iterator;
import java.util.Map;

import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamWriter;

public class StaxBuilder extends BuilderSupport {

	XMLStreamWriter writer;

	public StaxBuilder(XMLStreamWriter writer) {
		this.writer = writer;
	}

	public XMLStreamWriter getWriter() {
		return writer;
	}

	public void setWriter(XMLStreamWriter writer) {
		this.writer = writer;
	}

	protected Object createNode(Object name) {
		return createNode(name, null, null);
	}

	protected Object createNode(Object name, Object value) {
		return createNode(name, null, value);
	}

	protected Object createNode(Object name, Map attributes) {
		return createNode(name, attributes, null);
	}

	protected Object createNode(Object name, Map attributes,
			Object value) {
		try {
			writer.writeStartElement(name.toString());
			if (attributes != null) {
				for (Iterator iter = attributes.entrySet()
						.iterator(); iter.hasNext();) {
					Map.Entry entry = (Map.Entry) iter.next();
					writer.writeAttribute(entry.getKey()
							.toString(), entry.getValue()
							.toString());
				}
			}
			if (value != null) {
				writer.writeCharacters(value.toString());
			}
		} catch (XMLStreamException exception) {
			throw new RuntimeException(exception);
		}
		return name;
	}

	protected void nodeCompleted(Object parent, Object node) {
		try {
			writer.writeEndElement();
			if (parent == null) {
				writer.writeEndDocument();
				writer.flush();
			}
		} catch (XMLStreamException exception) {
			throw new RuntimeException(exception);
		}
	}

	protected void setParent(Object parent, Object child) {
	}
	
}
